<template>
  <div>
    <!-- 押金单待支付 -->
    <el-dialog
      v-el-drag-dialog
      title="押金待支付"
      :visible.sync="visible"
      width="1024px"
      append-to-body
      :destroy-on-close="false"
      @closed="reset"
    >
      <el-form ref="form" class="form" :model="temp" label-width="120px" label-position="right">
        <el-form-item label="押金单号:">
          <el-input
            v-model="temp.depositCode"
            disabled
          />
        </el-form-item>
        <el-form-item label="应支付金额:">
          <el-input
            v-model="treceivables"
            class="cred"
            disabled
          />
        </el-form-item>
        <el-form-item v-if="!showCode && show" label="请选择支付方式:" style="width: 100%;">
          <br>
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="微信" name="tencent">
              <div>
                <img src="../../../../assets/pay-wechat.gif" alt="">
                <div>支付界面在{{ count }}秒后关闭</div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="支付宝" name="alibaba">
              <div>
                <img src="../../../../assets/pay-zfb.gif" alt="">
                <div>支付界面在{{ count }}秒后关闭</div>
              </div>
            </el-tab-pane>
          </el-tabs>
          <el-input ref="inputCardCodeDom" v-model="inputCardCode" v-focus class="hide" @keydown.native="getCardCode" />
        </el-form-item>
      </el-form>
      <div v-if="temp.paymentMethod !== 1 && showCode && show" class="code-title">付款码</div>
      <div v-if="temp.paymentMethod !== 1 && showCode && show" class="code-img">
        <div ref="qrCodeUrl" />
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button v-if="temp.paymentMethod === 1" type="primary" @click="handleSave">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { queryByCode, payStatusSave, queryCheckDepozitPayStatus, getDepositPayPhoneCode } from '@/api'
  import QRCode from 'qrcodejs2'
  export default {
    name: 'gather',
    directives: {
      focus: {
        inserted: function(el) {
          el.querySelector('input').focus()
        }
      }
    },
    data() {
      return {
        visible: false,
        show: false,
        showCode: false,
        mode: 'qrcode', // 付款模式，qrcode扫码，box扫码盒子
        isPayStatus: false, // false初始值表示支付未成功,true表示支付成功
        base64Text: '',
        checkInterval: '',
        timeEndOut: 0,
        treceivables: 0,
        temp: {},
        inputCardCode: '', // 扫码盒子扫码完成后返回的字符串
        activeName: 'tencent',
        count: 60
      }
    },
    async created() {},
    methods: {
      open(temp) {
        // this.base64Text = ''
        const obj = {
          2: 'tencent', // 微信支付
          128: 'alibaba' // 支付宝
        }
        this.activeName = obj[temp.paymentMethod]
        this.temp = temp
        if (this.temp.paymentMethod !== 1) {
          this.gainQRCode(temp)
        }
        this.count = 60
        this.treceivables = this.temp.fee1 ? this.temp.totalDeposit + this.temp.fee1.toFixed(2) : this.temp.totalDeposit
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
        })
      },
      // 客户押金单支付获取微信/支付宝授权生成二维码
      async gainQRCode(temp) {
        const res = await queryByCode({
          orderCode: temp.depositCode,
          billType: 4
        })
        this.show = true
        if (res.message === '押金单可以收款' && res.status === 200) {
          this.showCode = false
          this.inputCardCode = ''
          if (this.treceivables === '0.00') {
            this.$message.warning('应支付金额为0,不支持' + this.activeName + '支付')
            return
          }
          this.$nextTick(() => {
            this.$refs.inputCardCodeDom.focus()
          })
          this.checkingPay2()
        } else {
          // const uuid = res.data.prePayId
          this.showCode = true
          const casService = `${res.data}`
          const codeUrl = casService
          this.creatQrCode(codeUrl)
          // 轮询开启
          this.timeEndOut = 1000
          this.checkingPay()
        }
      },
      async getCardCode(e) {
        console.log(e.keyCode)
        if (this.inputCardCode && e.keyCode === 13) {
          const res = await getDepositPayPhoneCode({
            paymentMethod: this.activeName === 'tencent' ? 2 : 128,
            payCardCode: this.inputCardCode,
            depositCode: this.temp.depositCode
          })
          this.inputCardCode = ''
          if (!res.code) {
            // 关闭轮序界面
            this.closeChecking()
            // 支付成功
            this.$message.info('支付成功')
            this.reset()
            return
          }
          const code = res.code
          if (code === 300) {
            this.transactionId = res.exc
            return
          }
          if (code === 500) {
            this.$message.error(res.exc)
            return
          }
        }
      },
      async creatQrCode(url) {
        setTimeout(() => {
          this.$refs.qrCodeUrl.innerHTML = ''
          new QRCode(this.$refs.qrCodeUrl, {
            text: url,
            width: 300,
            height: 300,
            colorDark: '#000000',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.Q
          })
        }, 500)
      },
      handleClick() {
        this.count = 60
      },
      // 定时器
      checkingPay() {
        const _this = this
        _this.checkInterval = setInterval(function() {
          if (_this.timeEndOut === 0) {
            clearInterval(_this.checkInterval)
          }
          if (_this.timeEndOut > 0) {
            var timeEndOut = _this.timeEndOut
            timeEndOut--
            _this.timeEndOut = timeEndOut
            _this.selectPayStatus()
          }
        }, 1000)
      },
      checkingPay2() {
        this.checkInterval = setInterval(() => {
          if (this.count === 0) {
            clearInterval(this.checkInterval)
            // 关闭界面
            this.visible = false
            return
          }
          this.count--
          // 请求次数：第一次2秒;第二次4秒;第三次8秒;第四次16秒;第五次32秒;第六次60秒;超过6次关闭界面
          if (this.count === 55 || this.count === 45 || this.count === 35 || this.count === 25 || this.count === 15 || this.count === 5) {
            // 调取招行支付结果,如果支付成功修改押金单
            this.selectDepositPayResult()
          }
        }, 1000)
      },
      // 支付轮询查看押金订单是否支付成功
      async selectPayStatus() {
        if (this.isPayStatus) { // 说明支付成功
          return
        }
        const res = await queryCheckDepozitPayStatus({ depositCode: this.temp.depositCode })
        if (res.data.payStatus === 3) { // 表示已支付
          this.closeChecking()
          // 支付成功,修改对应参数信息
          this.isPayStatus = false
          this.$message.info('支付成功')
          this.resolve(true)
          this.reset()
        }
      },
      async selectDepositPayResult() {
        if (!this.transactionId) {
          return
        }
        const params = {
          depcode: this.temp.depositCode,
          orderid: this.transactionId
        }
        const res = await this.selectDepositPayResult(params)
        if (!res.code) {
          // 关闭轮序界面
          this.closeChecking()
          // 支付成功
          this.$message.info('支付成功')
          this.resolve(true)
          this.reset()
          return
        }
      },
      closeChecking() {
        if (this.checkInterval !== null) {
          clearInterval(this.checkInterval)
          this.checkInterval = null
        }
      },
      async handleSave() {
        const res = await payStatusSave({ depositCode: this.temp.depositCode })
        if (res.status === 200) {
          this.$message.success('提交成功')
          this.resolve(true)
        }
        this.reset()
      },
      reset() {
        this.base64Text = ''
        this.checkInterval = ''
        this.timeEndOut = 0
        this.activeName = 'first'
        this.inputCardCode = ''
        this.closeChecking()
        this.isPayStatus = false
        this.visible = false
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  & /deep/ .el-form-item {
    width: 33%;
  }
  .block {
    width: 100%;
  }
  .el-tab-pane {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
  }
  .hide {
    width: 0;
    height: 0;
    /deep/ .el-input__inner {
      width: 0;
      height: 0;
      border: none;
    }
  }
}
.cred {
  /deep/ .el-input__inner {
    color: red !important;
  }
}
.mode-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  margin-top: 10px;
}
.code-title {
  width: 100%;
  font-size: 16px;
  text-align: center;
}
.code-img {
  display: flex;
  justify-content: center;
  width: 100%;
  margin-bottom: 10px;
}
</style>
